package com.blaze.framework.core.security;

import com.blaze.framework.core.security.util.TokenUtil;
import com.blaze.framework.core.util.constants.TokenConstants;
import com.blaze.framework.core.util.domain.TokenInfo;
import com.blaze.framework.core.util.uitls.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Optional;

/**
 * 用户本地上下文帮助类
 *
 * @author created by Zhou Zongbo on 2025/5/28.
 */
public class UserLocalContextHelper {

    private UserLocalContextHelper() {

    }

    /**
     * 从上下文中获取用户信息
     *
     * @return UserInfo
     */
    public static UserInfo getUserInfo() {
        return new UserInfo();
    }


    /**
     * 获取用户id
     * @return 用户id
     */
    public static Long getUserId() {
        Optional<HttpServletRequest> optHttpServletRequest = ServletRequestUtils.getHttpServletRequest();
        if (optHttpServletRequest.isEmpty()) {
            return null;
        }

        Enumeration<String> headers = optHttpServletRequest.get().getHeaders(TokenConstants.AUTHORIZATION);
        Iterator<String> iterator = headers.asIterator();
        while (iterator.hasNext()) {
            String headerItem = iterator.next();
            if (headerItem.startsWith(TokenConstants.AUTHORIZATION_BEARER)) {
                TokenInfo tokenInfo = TokenUtil.parseToken(headerItem);
                return tokenInfo.getUserId();
            }
        }
        return null;
    }
}
